package com.usian.wemedia.service.impl;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
@Log4j2
public class WmMaterialServiceImpl extends BaseServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    private String baseUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Override
    public ResponseResult uploadpicture(MultipartFile file) {
        //1.用户没有上传图片就报错给前端
        if(file == null)  return errorParam;

        //2.上传图片到fasfdfs
        String ImgUrl = null;
        try {
            ImgUrl = fastDFSClient.uploadFile(file);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(ImgUrl);

        //3.保存素材数据到表中 wm_material
        WmMaterial wmMaterial  = new WmMaterial();
        wmMaterial.setUserId(ThreadLocalUtils.getUserId());
        wmMaterial.setUrl(ImgUrl);
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

       //4.返回图片路径给前端
        return ResponseResult.okResult(baseUrl+ImgUrl);
    }



    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.用户没有选择就报错给前端
        if(dto == null) return errorParam;

        //2.带条件分页查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //3.通过head中的id,和前端用户id进行比对
        wrapper.eq(WmMaterial::getUserId,ThreadLocalUtils.getUserId());
        //4.是否收藏
        wrapper.eq(dto.getIsCollection()!=null,WmMaterial::getIsCollection,dto.getIsCollection());

        //5.按照日期倒序排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        //6.生成分页查询数据
        ResponseResult pageData = getPageData(dto, wrapper);

        //7.获取主体数据
        List<WmMaterial> list = (List<WmMaterial>) pageData.getData();
        //8.为每个图片加上前缀
        list.forEach(v->v.setUrl(baseUrl+v.getUrl()));

        //9.返回结果
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
       //1.判断id是否为空
       if(id == null) return errorParam;
       //2.type为空，或 不等于1 和 不等于0
       if(type == null || (type !=0 && type !=1)) return errorParam;
       //3.更新状态,根据当前素材列表id
       update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type)
               .eq(WmMaterial::getId,id));
       //4.成功
        return success;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        //1.判断id是否为空
       if(id == null) return errorParam;
       //2.获取当前素材列表id对象
       WmMaterial material = getById(id);
       //3.为空，报不存在
       if(material == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"你删除的素材不存在");
       //4.查询有几条引用素材表图片的条数
        Integer count =  wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId,id));
        //5. 有，报已引用
        if(count>0) return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该素材已被引用");
        //6.没有引用，获取fastdfs+图片路径
        String url = material.getUrl();
        //7.删除文件服务器内的图片路径
        fastDFSClient.delFile(url);
        //8.在删除数据库中当前素材id对象
        removeById(id);
        //9.返回成功
        return success;
    }
}
